//
//  OACellConfig+ViewModelManager.m
//  OASDK_Works
//
//  Created by ChenJie on 5/23/20.
//  Copyright © 2020 Mist. All rights reserved.
//

#import "OACellConfig+ViewModelManager.h"
#import <objc/runtime.h>
#import <MJExtension/MJExtension.h>

@implementation OACellConfig (ViewModelManager)

+ (id<OACellViewModelProtocol>)cellViewModelWithCellType:(NSString *)cellType
                                           viewModelInfo:(id)viewModelInfo {
    
    // nil
    if (!viewModelInfo) {
        Class cellViewModelClass = [self cellViewModelClassWithCellType:cellType];
        return [[cellViewModelClass alloc] init];
    }
    
    // cell viewModel
    if ([viewModelInfo conformsToProtocol:@protocol(OACellViewModelProtocol)]) {
        return viewModelInfo;
    }
    
    // dictionary
    if ([viewModelInfo isKindOfClass:NSDictionary.class]) {
        Class cellViewModelClass = [self cellViewModelClassWithCellType:cellType];
        id<OACellViewModelProtocol> cellViewModel = [cellViewModelClass mj_objectWithKeyValues:viewModelInfo];
        return cellViewModel;
    }
    
    return nil;
}

+ (Class)cellViewModelClassWithCellType:(NSString *)cellType {
    
    // cellType + ViewModel
    NSString *cellViewModelClassName = [cellType stringByAppendingString:@"ViewModel"];
    Class cellViewModelClass = NSClassFromString(cellViewModelClassName);
    if (cellViewModelClass) {
        return cellViewModelClass;
    }
    
    // property viewModel
    Class cellClass = NSClassFromString(cellType);
    NSString *viewModelClassName;
    if (cellClass) {
        unsigned int propertyCount = 0;
        objc_property_t *properties = class_copyPropertyList(cellClass, &propertyCount);
        for (NSInteger i = 0; i < propertyCount; i ++) {
            objc_property_t property = properties[i];
            NSString *propertyName = [NSString stringWithUTF8String:property_getName(property)];
            if ([propertyName isEqualToString:@"viewModel"]) {
                NSString *propertyAttribute = [NSString stringWithUTF8String:property_getAttributes(property)];
                NSUInteger commaLocation = [propertyAttribute rangeOfString:@","].location;
                NSUInteger classNameLocation = 3;
                if (commaLocation == NSNotFound) { // no comma
                    viewModelClassName = [propertyAttribute substringFromIndex:classNameLocation];
                } else {
                    NSRange classNameRange = NSMakeRange(classNameLocation, commaLocation - 1 - classNameLocation);
                    viewModelClassName = [propertyAttribute substringWithRange:classNameRange];
                }
                break;
            }
        }
        free(properties);
    }
    
    cellViewModelClass = NSClassFromString(viewModelClassName);
    if (cellViewModelClass) {
        return cellViewModelClass;
    }
    
    return nil;
}

@end
